package com.feiyuan.filter;

import com.alibaba.fastjson.JSONObject;
import com.feiyuan.common.utils.JWTUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 后台过滤器
 */
@Component
@WebFilter(urlPatterns = {"/*"}, filterName = "AdminLoginFilter")
@Order(2)
public class AdminLoginFilter implements Filter {

    private Logger logger = LoggerFactory.getLogger(AdminLoginFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("==============初始化过滤器=================");
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String uri = request.getRequestURI();
        logger.info("uri:{}", uri);
        if (uri.contains("/admin/login/") || uri.indexOf("/api/") == 0 || uri.contains("/test/")) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        String method = request.getMethod();
        if ("OPTIONS".equals(method)) {
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        Map<String, Object> map = new HashMap<>();

        // 检查用户是否登录
        String token = request.getHeader(JWTUtils.ACCESS_TOKEN);
        logger.info("token:{}", token);
        if (StringUtils.isEmpty(token)) {
            // 请重新登录
            map.put("code", 10010);
            map.put("message", "请重新登录");
        } else {
            // 通过JWT验证
            if (!JWTUtils.checkToken(token)) {
                // 请重新登录
                map.put("code", 10010);
                map.put("message", "请重新登录");
            } else {
                filterChain.doFilter(servletRequest, servletResponse);
                return;
            }
        }

        //使用response返回
        response.setStatus(HttpStatus.OK.value()); //设置状态码
        response.setContentType(MediaType.TEXT_PLAIN_VALUE); //设置ContentType
        response.setCharacterEncoding("UTF-8"); //避免乱码
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        try {
            response.getWriter().write(JSONObject.toJSONString(map));
        } catch (IOException e) {
            logger.error("与客户端通讯异常:"+ e.getMessage(), e);
        }
    }

    @Override
    public void destroy() {
        logger.info("==============销毁过滤器=================");
        Filter.super.destroy();
    }
}
